package org.example

object Library {
  def apply(books: Book*): Library = {
    new Library(books.toList)
  }
}

class Library(private var books: List[Book] = Nil) {
  def addBook(book: Book): Unit = {
    books = book :: books
  }

  def borrowBook(isbn: String): Unit = {
    val index = findBookByindex(isbn)
    if (index >= 0) {
      val book = books(index)
      if (!book.borrowed) {
        book.borrow()
        println(s"书已经 $isbn 被借.")
      } else {
        println("书不可用")
      }
    } else {
      println("书没有找到.")
    }
  }

  def returnBook(isbn: String): Unit = {
    val index = findBookByindex(isbn)
    if (index >= 0) {
      val book = books(index)
      if (book.borrowed) {
        book.returnBook()
        println(s"书 $isbn 被归还")
      } else {
        println("书已经被借走了")
      }
    } else {
      println("书没有找到")
    }
  }

  private def findBookByindex(isbn: String): Int = {
    var index = 0
    while (index < books.length && books(index).isbn != isbn) {
      index += 1
    }
    if (index < books.length) index else -1
  }
}

